<template>
  <el-form ref="ruleFormRef" :model="formData" :rules="rules" :label-width="formConfig.labelWidth" :size="formConfig.size">
    <el-form-item :label="item.label + ':'" :prop="item.prop" v-for="item in formItems" :key="item.prop">
      <component
        :is="ItemMap[item.name]"
        :item-config="item"
        :item-value="formData[item.prop]"
        :corr-value="item.corrProp ? formData[item.corrProp] : null"
        :ref="item.prop"
        @update="handleUpdate"
      />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
  import { PropType, toRefs, reactive, ref } from 'vue';
  import { BaseFormItem, FormConfigType } from './common-form-type';
  import { ItemMap } from './items';
  // 声明 类型
  interface FD {
    fd: any;
    rules: any;
  }

  // 预处理方法 - 初始化 formData 和 rules
  const initFormData = (arr: Array<BaseFormItem>): FD => {
    let fd: any = {};
    let rules: any = {};

    arr.forEach((item) => {
      fd[item.prop] = item.defaultValue;
      rules[item.prop] = item.rules;
    });

    return { fd, rules };
  };
  // 接收子组件回调 - 更新数据
  const handleUpdate = (c: any): void => {
    formData[c.prop] = c.val;
  };

  // 获取 props
  const props = defineProps({
    formItems: {
      type: Array as PropType<Array<BaseFormItem>>,
      default: () => [{ name: 'input', prop: 'username', label: '用户名', placeholder: '请输入用户名' }],
    },
    formConfig: { type: Object as PropType<FormConfigType>, default: () => ({}) },
  });

  // 初始化data
  const inited = ref(true);
  const ruleFormRef = ref(); // 表单 Ref
  const { formItems, formConfig } = toRefs(props);
  const formData = reactive(initFormData(formItems.value).fd); // 绑定 formData
  const rules = reactive(initFormData(formItems.value).rules); // 绑定 rules

  const getValue = () => {
    let validateRusult = false;
    ruleFormRef.value &&
      ruleFormRef.value.validate((v: boolean) => {
        if (v) {
          console.warn('submit');
          validateRusult = true;
        } else {
          console.error('submit fiald!', formData);
          validateRusult = false;
        }
      });
    return validateRusult ? formData : false;
  };

  // 为表单赋值
  const setFormData = (val: any) => {
    console.log('🚀 ~ file: Former.vue ~ line 76 ~ setFormData ~ val', val);

    inited.value = false;
    for (let key in val) {
      console.log('🚀 ~ file: Former.vue ~ line 80 ~ setFormData ~ key', key);

      formData[key] = val[key];
    }
    inited.value = true;
  };

  const reset = () => {
    ruleFormRef.value.resetFields();
  };

  defineExpose({ getValue, formData, reset, setFormData });
</script>
